package com.ruoyi.common.wx;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.util.RandomUtil;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.utils.http.HttpUtils;
import com.wechat.pay.java.core.Config;
import com.wechat.pay.java.core.RSAAutoCertificateConfig;
import com.wechat.pay.java.service.transferbatch.TransferBatchService;
import com.wechat.pay.java.service.transferbatch.model.InitiateBatchTransferRequest;
import com.wechat.pay.java.service.transferbatch.model.InitiateBatchTransferResponse;
import com.wechat.pay.java.service.transferbatch.model.TransferDetailInput;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.math.BigDecimal;
import java.util.Collections;
import java.util.Date;

public class WxApi {

    private static final Logger log = LoggerFactory.getLogger(WxApi.class);

    // 小程序appId
    private static String appId = "wxd0e9c6716f5ca79e";

    // 小程序密钥
    private static String secret = "1610603cf42f428b52f20cc6db7372b4";

    // 获取用户openId请求地址
    private static String serverUrl = "https://api.weixin.qq.com/sns/jscode2session";

    private static String testOpenId = "orUr85PkQFYu2Zjg5GcS8DdtQei0";

    // 商户号
    public static String merchantId = "1568393541";

    // 商户API私钥路径
//    public static String privateKeyPath = "H:\\workSpace\\hankai\\1568393541_20201229_cert\\apiclient_key.pem";
    public static String privateKeyPath = "/www/wwwroot/comment_test/wxCert/apiclient_key.pem";

    // 商户证书序列号
    public static String merchantSerialNumber = "6EA32691C512A611202A1C37C62425EB6A1D89DA";

    // 商户APIV3密钥
    public static String apiV3Key = "5d93ceb70e2bf5daa84ec3d0cd2c731a";


    /**
     * 小程序通过code获取用户openId
     *
     * @param code
     * @return
     */
    public static String getWxUserOpenId(String code) {
        String reqStr = "appid=" + appId + "&secret=" + secret + "&js_code=" + code + "&grant_type=authorization_code";
        String response = HttpUtils.sendGet(serverUrl, reqStr);
        JSONObject resObj = JSONObject.parseObject(response);
        if (resObj.getInteger("errcode") == null) {
            return resObj.getString("openid");
        } else {
            log.error("获取openId失败，返回参数为：{}", response);
            return null;
        }
    }

    /**
     * 商家转账到零钱
     *
     * @param withdrawAmount
     * @param openId
     * @param userName
     */
    public static InitiateBatchTransferResponse transferToUser(String openId, String userName, BigDecimal withdrawAmount) {
        Config config =
                new RSAAutoCertificateConfig.Builder()
                        .merchantId(merchantId)
                        // 使用 com.wechat.pay.java.core.util
                        // 中的函数从本地文件中加载商户私钥，商户私钥会用来生成请求的签名
                        .privateKeyFromPath(privateKeyPath)
                        .merchantSerialNumber(merchantSerialNumber)
                        .apiV3Key(apiV3Key)
                        .build();
        // 初始化服务
        TransferBatchService service = new TransferBatchService.Builder().config(config).build();
        InitiateBatchTransferRequest request = new InitiateBatchTransferRequest();
        request.setAppid(appId);
        String bizNo = "O" + DatePattern.PURE_DATETIME_FORMAT.format(new Date()) + RandomUtil.randomString(4);
        request.setOutBatchNo(bizNo);
        request.setBatchName("客户提现");
        request.setBatchRemark("客户回收提现");
        //单位为分
        long amount = withdrawAmount.multiply(new BigDecimal(100)).longValue();
        request.setTotalAmount(amount);
        request.setTotalNum(1);
        TransferDetailInput transferDetailInput = new TransferDetailInput();
        String detailNo = "O" + DatePattern.PURE_DATETIME_FORMAT.format(new Date()) + RandomUtil.randomString(4);
        transferDetailInput.setOutDetailNo(detailNo);
        transferDetailInput.setTransferAmount(amount);
        transferDetailInput.setTransferRemark("回收提现");
        transferDetailInput.setOpenid(openId);
        transferDetailInput.setUserName(userName);
        request.setTransferDetailList(Collections.singletonList(transferDetailInput));
        InitiateBatchTransferResponse transferResponse = service.initiateBatchTransfer(request);
        log.info("微信提现，返回参数为：{}", transferResponse.toString());
        return transferResponse;
    }

    public static void main(String[] args) {
        transferToUser(testOpenId, "韩凯", new BigDecimal("0.3"));
    }

}
